package com.waqwb.dao.impl;

import com.waqwb.dao.UserDAO;
import com.waqwb.entity.User;
import com.waqwb.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author JokerQ
 * @date 2020/7/15 - 11:54
 */
public class UserDAOImpl implements UserDAO {
    @Override
    public User getUserByEmail(String email) {
        User user = null;
        try {
            Connection con = DBUtil.getConnection();
            String sql = "select * from d_user where email=?";
            PreparedStatement prep = con.prepareStatement(sql);
            prep.setString(1, email);
            ResultSet rs = prep.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setEmail(rs.getString("email"));
                user.setNickname(rs.getString("nickname"));
                user.setPassword(rs.getString("password"));
            }
            DBUtil.close(rs, prep, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public void saveUser(User user) {
        try {
            Connection con= DBUtil.getConnection();
            String sql="insert into d_user(email,nickname,password) values(?,?,?)";
            PreparedStatement prep=con.prepareStatement(sql);
            prep.setString(1, user.getEmail());
            prep.setString(2, user.getNickname());
            prep.setString(3, user.getPassword());
            prep.executeUpdate();
            DBUtil.close(null, prep, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User getUser(String email, String password) {
        User user=null;
        try {
            Connection con= DBUtil.getConnection();
            String sql="select * from d_user where email=? and password=?";
            PreparedStatement prep=con.prepareStatement(sql);
            prep.setString(1, email);
            prep.setString(2, password);
            ResultSet rs= prep.executeQuery();
            if(rs.next()){
                user=new User();
                user.setEmail(rs.getString("email"));
                user.setPassword(rs.getString("password"));
                user.setId(rs.getInt("id"));
                user.setNickname(rs.getString("nickname"));
            }
            DBUtil.close(null, prep, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
